<?php

class RegularUpdatesTask extends sfBaseTask
{
    protected function configure()
    {
        $this->addOptions(array(
            new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environement', 'prod'),
        ));
        
        $this->namespace = 'updates';
        $this->name = 'regular';
        $this->briefDescription = 'Run all pending requested updates. If there\'s none, run updates for all sources that haven\'t been updated for a day.';
        $this->detailedDescription = '';
    }
    
    protected function execute($arguments = array(), $options = array())
    {
        // Required to allow database queries
        $databaseManager = new sfDatabaseManager($this->configuration);
        
        LogHelper::log("Checking for pending runs.");
        
        $pendingRuns = Doctrine_Core::getTable('SourceRefreshRun')
                ->createQuery('srr')
                ->where('srr.requested_date IS NOT NULL')
                ->andWhere('srr.start_date IS NULL')
                ->orderBy('srr.requested_priority DESC, srr.requested_date')
                ->execute();
        if ($pendingRuns->count() > 0) {
            $startTime = time();
            
            foreach ($pendingRuns as $pendingRun) {
                LogHelper::log("Completing run " . $pendingRun->getId() . ".");
                
                $result = SourceUpdates::completeRun($pendingRun);
                
                LogHelper::log('Run ' . $pendingRun->getId() . ' finished. Attempted = ' . ($result['attempted'] ? 'true' : 'false') . ', already running = ' . ($result['alreadyRunning'] ? 'true' : 'false') . ', completed = ' . ($result['completed'] ? 'true' : 'false') . ', error = ' . ($result['error'] ? 'true' : 'false'));
                
                // If after completing a pending run this job has taken more than 10 minutes, then finish. We'll pick up any
                // still outstanding runs in the next check.
                if (time() > ($startTime + Config::$cronJobCheckFrequency)) {
                    break;
                }
            }
        }
        else {
            $startTime = time();
            
            LogHelper::log("No pending runs. Checking for sources due for an update.");
            
            $sourcesToUpdate = Doctrine_Core::getTable('Source')
                ->createQuery('s')
                ->where('s.id NOT IN (SELECT srr.source_id FROM SourceRefreshRun srr WHERE srr.end_date > ?)', array(date('Y-m-d H:i:s', (time() - Config::$regularUpdateFrequency))))
                ->andWhere('s.allow_updates = 1')
                ->execute();
            foreach ($sourcesToUpdate as $sourceToUpdate) {
                
                LogHelper::log('Running update for sourceId = ' . $sourceToUpdate->getId());
                
                $result = SourceUpdates::newRun($sourceToUpdate->getId());
        
                LogHelper::log('Finished. Attempted = ' . ($result['attempted'] ? 'true' : 'false') . ', already running = ' . ($result['alreadyRunning'] ? 'true' : 'false') . ', completed = ' . ($result['completed'] ? 'true' : 'false') . ', error = ' . ($result['error'] ? 'true' : 'false'));
                
                // If after completing a new run this job has taken more than 10 minutes, then finish. We'll pick up any
                // other sources due for a run in the next check.
                if (time() > ($startTime + Config::$cronJobCheckFrequency)) {
                    break;
                }
            }
        }
        
        LogHelper::log("Done.");
        echo "Done." . PHP_EOL;
    }
}